package cn.tedu.util;

import java.io.*;

public class CloneModule {
    private String srcKey;
    private String targetKey;

    public CloneModule(String srcKey, String targetKey) {
        this.srcKey = srcKey;
        this.targetKey = targetKey;
    }

    public void copy(String srcPath, String targetPath) throws IOException {
        File file = new File(srcPath);
        File target = new File(targetPath);
        if (!target.isDirectory()) {
            return;
        }
        deleteDir(new File(target, trans(file.getName())));
        walkFile(file, target);
    }

    private void walkFile(File file, File target) throws IOException {
        if (file == null) {
            return;
        }
        String name = file.getName();
        String targetName = name.replaceFirst(srcKey, targetKey);
        File targetFile = new File(target, targetName);
        if (file.isDirectory()) {
            if (targetFile.exists()) {
                targetFile.delete();
            }
            targetFile.mkdir();
            File[] files = file.listFiles();
            for (File f : files) {
                walkFile(f, targetFile);
            }
        } else {
            copy(file, targetFile);
        }
    }

    private void copy(File src, File target) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(src)));
        PrintWriter printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(target))));
        String line = bufferedReader.readLine();
        while (line != null) {
            printWriter.println(trans(line));
            line = bufferedReader.readLine();
        }
        bufferedReader.close();
        printWriter.close();
    }

    private String trans(String ori) {
        return ori.replaceAll(srcKey, targetKey);
    }

    private void deleteDir(File file) {
        if (file != null) {
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File f : files) {
                    deleteDir(f);
                }
                file.delete();
            } else {
                file.delete();
            }
        }

    }
}
